package com.lin.netty.practice;

import ch.qos.logback.core.encoder.EchoEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

@Slf4j
public class EchoClient {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup workers = new NioEventLoopGroup();
        Channel channel = bootstrap
                .group(workers)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("stringDecoder", new StringDecoder());

                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                log.debug("收到服务器消息：{}", msg);
                            }
                        });

                        ch.pipeline().addLast("encoder", new StringEncoder());
                    }
                })
                .connect("127.0.0.1", 1122)
                .sync()
                .channel();

        log.debug("连接成功：{}", channel);
        while (true) {
            Scanner scanner = new Scanner(System.in);
            String msg = scanner.nextLine();
            if ("q".equals(msg)) {
                workers.shutdownGracefully();
                break;
            }

            log.debug("给服务器发送数据：{}", msg);
            channel.writeAndFlush(msg);

        }
    }
}
